package com.ruoyi.xag.utils;

import org.junit.Test;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


/**
 * @author Mr-Le
 * 生成签名（物理网设备-气象土壤传感器）
 */
public class CreateSignature {

    /**
     * 获取 Signature ，单个有效期 12 小时，产生新值，旧值失效
     *
     * @param secret 账户密钥 由配置文件获得
     * @return 签名字符串
     */
    public static String getSignature(String secret) {
        Long timestamp = System.currentTimeMillis() / 1000;
        String nonce = CreateSignature.randomCreateStr();
        return getSignature((timestamp + nonce), secret);
    }


    /**
     * 随机生产6位字符串 (小写字母)
     * 生成的随机数范围（0-1）* 26 + 97(小写字母 a 的 Ascll码值 97)  压缩在 a - z
     *
     * @return 合成后的字符串
     */
    private static String randomCreateStr() {
        String result = "";
        for (int i = 0; i < 6; i++) {
            int intVal = (int) (Math.random() * 26 + 97);
            result += (char) intVal;
        }
        return result;
    }

    /**
     * 生成签名数据
     *
     * @param data 待加密的数据
     * @param key  加密使用的key
     * @return
     */
    private static String getSignature(String data, String key) {
        try {
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : rawHmac) {
                sb.append(byteToHexString(b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 字节转16进制字符串
     * 通过判断
     *
     * @param b byte
     * @return 字符串类型
     */
    private static String byteToHexString(byte b) {
        char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] ob = new char[2];
        ob[0] = digit[(b >>> 4) & 0X0f];
        ob[1] = digit[b & 0X0F];
        String s = new String(ob);
        return s;
    }

    /**
     * 合并鉴权参数 URL 地址
     * @param clientId 客户ID
     * @param secret 唯一密钥
     * @return URL后半截
     */
    public static String mergeAuthenticationUrl(String clientId, String secret) {
        Long timestamp = System.currentTimeMillis() / 1000;
        String nonce = randomCreateStr();
        String signature = getSignature((timestamp + nonce), secret);
        return "?timestamp=" + timestamp + "&client_id=" + clientId + "&nonce=" + nonce + "&signature=" + signature;
    }

    /*    public static String splitMax() {
        String ClientId = "juogMu8jJBo";
        String secret = "ccc3e0fdb56873c9";
        Long timestamp = System.currentTimeMillis() / 1000;
        String nonce = randomCreateStr();
        String signature = getSignature((timestamp + nonce), secret);
        return "?timestamp=" + timestamp + "&client_id=" + ClientId + "&nonce=" + nonce + "&signature=" + signature;
    }*/
}
